package kitwee.com.kanpad;

import android.app.Activity;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.blankj.utilcode.util.Utils;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
//import com.qihoo.appstore.common.updatesdk.lib.UpdateHelper;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import kitwee.com.kanpad.orderDetail.SerialPortHelper;
import kitwee.com.kanpad.orderDetail.SerialPortPreferences;
import okhttp3.OkHttpClient;


/**
 * Created by sven on 2017/3/28.
 */

public class MyMultiDexApplication extends MultiDexApplication {
    private static MyMultiDexApplication instance;
    private static Context context;

    public static Context getContext() {
        return context;
    }


    /**
     * 打开的activity
     **/
    private List<Activity> activities = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();

//        UpdateHelper.getInstance().init(getApplicationContext(), Color.parseColor("#0A93DB"));


        context = getApplicationContext();
        instance = this;
        Utils.init(this);

        //PushService.start(context);


        //UpdateHelper.getInstance().init(this, Color.parseColor("#0A93DB"));
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG"))
                .readTimeout(10000L, TimeUnit.MILLISECONDS);

//        if (BuildConfig.DEBUG) {
            Stetho.initializeWithDefaults(this);
            builder.addNetworkInterceptor(new StethoInterceptor());
//        }
        OkHttpUtils.initClient(builder.build());
        //腾讯bugly统计
        initBugly();

        autoUpdate();
        SerialPortPreferences.initialize(getApplicationContext());

        final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                //获取崩溃时的UNIX时间戳
                long timeMillis = System.currentTimeMillis();
                //将时间戳转换成人类能看懂的格式，建立一个String拼接器
                StringBuilder stringBuilder = new StringBuilder(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(timeMillis)));
                stringBuilder.append(":\n");
                //获取错误信息
                stringBuilder.append(throwable.getMessage());
                stringBuilder.append("\n");
                //获取堆栈信息
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                stringBuilder.append(sw.toString());

                //这就是完整的错误信息了，你可以拿来上传服务器，或者做成本地文件保存等等等等
                String errorLog = stringBuilder.toString();

                //最后如何处理这个崩溃，这里使用默认的处理方式让APP停止运行
                defaultHandler.uncaughtException(thread, throwable);
            }
        });
    }

    private void initBugly() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, "2104177e4d", false, strategy);
    }

    private void autoUpdate() {
        long intervalMillis = 10 * 1000L;
        String packageName = context.getPackageName();
//        LogUtils.e("packageName : " + packageName);
//        UpdateHelper.getInstance().autoUpdate(packageName,
//                true, intervalMillis);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //PushService.stop(context);

        // 停止串口服务
        SerialPortHelper.getInstance(this).closeSerialPort();
    }

    public MyMultiDexApplication() {
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static MyMultiDexApplication getInstance() {
        return instance;
    }

    /**
     * 新建了一个activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activities.add(activity);
    }

    /**
     * 结束指定的Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            this.activities.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 应用退出，结束所有的activity
     */
    public void exit() {
        for (Activity activity : activities) {
            if (activity != null) {
                activity.finish();
            }
        }
        System.exit(0);
    }

    /**
     * 关闭Activity列表中的所有Activity
     */
    public void finishActivity() {
        for (Activity activity : activities) {
            if (null != activity) {
                activity.finish();
            }
        }
        //杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
